//
//  EpisodeAPI.swift
//  WBDemo
//
//  Created by Jin on 26/04/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import Foundation

//定义一个包含api版本信息的类型
struct EpisodeCodingOptions{
    enum Version {
        case v1
        case v2
    }
    
    let apiVersion:Version
    let dateFormatter:DateFormatter
    
    //生成key对象
    static let infoKey = CodingUserInfoKey(rawValue: "io.boxue.episode-coding-options")!
    
}

struct EpisodeAPI: Codable {
    var createdAt:Date
    
    enum CodingKeys:String,CodingKey {
        case createdAt = "created_at"
    }
    
    init(from decoder:Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let createdAt = try container.decode(Date.self, forKey: .createdAt)
        self.init(createdAt: createdAt)
    }
    
    init(createdAt:Date) {
        self.createdAt = createdAt
    }
}

extension EpisodeAPI{
    func encode(to encoder:Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if let options = encoder.userInfo[EpisodeCodingOptions.infoKey] as? EpisodeCodingOptions {
            let date = options.dateFormatter.string(from: createdAt)
            try container.encode(date, forKey: .createdAt)
        }
    }
}
